//
//  ImageScrollViewController.m
//  BosidengIphone
//
//  Created by  on 12-1-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ImageScrollViewController.h"
#define PADDING  0
#define TAG_BASE 100

@implementation ImageScrollViewController
@synthesize pagingScrollView;
@synthesize canHanlderPageSingleTap;
@synthesize loadAtFirst;

- (CGRect)frameForPagingScrollView {
    CGRect frame = [[UIScreen mainScreen] bounds];
    frame.origin.x -= PADDING;
    frame.size.width += (2 * PADDING);
    return frame;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //currentPageIndex = -1;
        self.canHanlderPageSingleTap = YES;
        self.loadAtFirst = YES;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */

- (CGSize)contentSizeForPagingScrollView {
    // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
    CGRect bounds = pagingScrollView.bounds;
    return CGSizeMake(bounds.size.width * [self imageCount], bounds.size.height);
}

///*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    pagingScrollView.pagingEnabled = YES;
    pagingScrollView.backgroundColor = [UIColor blackColor];
    pagingScrollView.showsVerticalScrollIndicator = NO;
    pagingScrollView.showsHorizontalScrollIndicator = NO;
    //pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    pagingScrollView.delegate = self;
    
    if (canHanlderPageSingleTap) {
        //单击事件
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        singleTap.numberOfTapsRequired = 1;
        [pagingScrollView addGestureRecognizer:singleTap];
        [singleTap release];
    }
    
    // Step 2: prepare to tile content
    recycledPages = [[NSMutableSet alloc] init];
    visiblePages  = [[NSMutableSet alloc] init];
    if (loadAtFirst) {
        [self loadPageViews];
    }
}
//*/

- (void)loadPageViews {
    for (UIView *view in recycledPages) {
        [view removeFromSuperview];
    }
    [recycledPages removeAllObjects];
    
    for (UIView *view in visiblePages) {
        [view removeFromSuperview];
    }
    [visiblePages removeAllObjects];
    
    currentPageIndex = -1;
    pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    [self tilePages];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.pagingScrollView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [pagingScrollView release];
    [recycledPages release];
    recycledPages = nil;
    [visiblePages release];
    visiblePages = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark Tiling and page configuration

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
    // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
    // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
    // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
    // because it has a rotation transform applied.
    CGRect bounds = pagingScrollView.bounds;
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + PADDING;
    return pageFrame;
}

- (void)tilePages 
{
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = pagingScrollView.frame.size.width;
    int page = floor((pagingScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    page = MAX(page, 0);
    page  = MIN(page, [self imageCount] - 1);
    //NSLog(@"currentPage=%d, page=%d", currentPageIndex, page);
    if (currentPageIndex != page) {
        currentPageIndex = page;
        [self changePageIndex:page];
    }
    
    // Calculate which pages are visible
    CGRect visibleBounds = pagingScrollView.bounds;
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds)) - 1;
    int lastNeededPageIndex  = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds)) + 1;
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex  = MIN(lastNeededPageIndex, [self imageCount] - 1);
    
    int index;
    // Recycle no-longer-visible pages 
    for (UIView *page in visiblePages) {
        index = page.tag - TAG_BASE;
        if (index < firstNeededPageIndex || index > lastNeededPageIndex) {
            [recycledPages addObject:page];
            [page removeFromSuperview];
        }
    }
    [visiblePages minusSet:recycledPages];
    //NSLog(@"display photo index(%d - %d)", firstNeededPageIndex, lastNeededPageIndex);
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            UIView *page = [self dequeueRecycledPage];
            page = [self configureView:page atIndex:index];
            page.tag = TAG_BASE + index;
            page.frame = [self frameForPageAtIndex:index];
            [pagingScrollView addSubview:page];
            [visiblePages addObject:page];
        }
    }    
}

- (UIView *)dequeueRecycledPage
{
    UIView *page = [recycledPages anyObject];
    if (page) {
        [[page retain] autorelease];
        [recycledPages removeObject:page];
    }
    return page;
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    BOOL foundPage = NO;
    for (UIView *page in visiblePages) {
        if (page.tag == (TAG_BASE + index)) {
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}

#pragma mark -
#pragma mark ScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self tilePages];
}

//单击事件
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
    [self selectPageIndex:currentPageIndex];
}

- (NSInteger)imageCount {
    return 0;
}

- (UIView *)configureView:(UIView *)page atIndex:(NSInteger)index {
    return nil;
}

- (void)changePageIndex:(NSInteger)index {
    ;
}

- (void)selectPageIndex:(NSInteger)index {
    ;
}

@end
